import { loginAPI, profileAPI, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'

const state = {
  token: '',
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
  },

  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
    state.token = ''
    // 重置路由，高权限路由退出不刷新低权限路由登录导致路由不刷新，调用函数强制刷新
    resetRouter()
  }

}
const actions = {
  // 登录
  async login(context, data) {
    const res = await loginAPI(data)
    context.commit('setToken', res.data)
    localStorage.setItem('tokenTime', Date.now())
    return res
  },
  // 管理员基本数据
  async getUserInfo(context) {
    const res = await profileAPI()
    const result = await getUserDetailById(res.data.userId)
    const baseResult = { ...res.data, ...result.data }
    context.commit('setUserInfo', baseResult)
    return baseResult
  },
  async logout(context) {
    await context.commit('removeUserInfo')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
